/****
	Copyright 2011 Taras Kulbachka

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package com.atdevsoft.apps.abyss;

import com.atdevsoft.apps.abyss.utils.AbyssViewPager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class QuotesActivity extends Activity {	
	public static final String ACTION_NEED_REFRESH_DATA = "com.atdevsoft.apps.abyss.ACTION_NEED_REFRESH_DATA";
	public static final String INTENT_EXTRA_REFRESH_TYPE = "refresh_type";
	
	public static final int REFRESH_TYPE_FULL = 1;
	public static final int REFRESH_TYPE_SET_NEXT_PAGE = 2;
	
	public static final int COLOR_SCHEME_UNSET = 0;
	public static final int COLOR_SCHEME_BLACK = 1;
	public static final int COLOR_SCHEME_WHITE = 2;
	
	private QuotesNavigator mQuotesNavigator = null;
	
	private BroadcastReceiver downloadDoneReceiver = new BroadcastReceiver() {        
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    		    	
	    	int totalQuotesAdded = intent.getExtras().getInt(AbyssDownloaderService.INTENT_EXTRA_QUOTES_ADDED);   	
	    	if (totalQuotesAdded > 0) {
	    		Dialog d = new AlertDialog.Builder(mContext)
	            	.setTitle(R.string.download_finished_dialog_title)
	            	.setMessage(String.format(mContext.getString(R.string.download_finished_dialog), totalQuotesAdded))
	            	.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
	            		public void onClick(DialogInterface dialog, int whichButton) {
	            			mQuotesNavigator.setTopQuote(QuotesNavigator.VERY_FIRST_QUOTE);
	            		}
	            	})
	            	.setNegativeButton(R.string.no, null)
	            	.create();		    	
	    		d.show();
	        }
	    }
	};	
	
	private BroadcastReceiver refreshNeeded = new BroadcastReceiver() {        
	    @Override
	    public void onReceive(Context context, Intent intent) {	    	
	    	if (!mQuotesNavigator.getCurrentTableName().equals("")) {
	    		int refreshType = intent.getExtras().getInt(INTENT_EXTRA_REFRESH_TYPE, REFRESH_TYPE_FULL);
	    		switch (refreshType) {
	    		case REFRESH_TYPE_FULL: 
	    			fullRefresh();
	    			break;
	    		case REFRESH_TYPE_SET_NEXT_PAGE:
	    			int page = mPager.getCurrentItem();
	    			if (page < mQuotesNavigator.getTotalPagesCount()) {
	    				mPager.setCurrentItem(page + 1, true);
	    			}
	    			break;
	    		}
	    	}	    	
	    }
	};		
	
	public static final String LAST_VISIBLE_SUFFIX_ABYSS_BEST = "";
	public static final String LAST_VISIBLE_SUFFIX_FAVORITES = "-favs";	

	
	private int mColorScheme;
	
	private ImageButton mBtnFirst;
	private ImageButton mBtnLast;
	private ImageButton mBtnQuotesSource;
	
	private SharedPreferences mPreferences;
	private Context mContext;	
	
	private String mCurrentLastVisibleSuffix = LAST_VISIBLE_SUFFIX_ABYSS_BEST;	
    
    private AbyssViewPager mPager;
    

    private void fullRefresh() {
    	saveTopVisible();
		int pos = mPreferences.getInt("top-visible" + mCurrentLastVisibleSuffix, QuotesNavigator.VERY_FIRST_QUOTE);
		//setting table instead of just quote num will force to refresh pages count which may change
		mQuotesNavigator.setCurrentTable(mQuotesNavigator.getCurrentTableName(), pos);    	
    }

    private void scrollListView(int delta) {  
        mPager.scrollListView(delta); 
    } 

    private void checkColorScheme() {
    	boolean isWhite = mPreferences.getBoolean("prefs_white_scheme", false);
    	
    	if ((isWhite && (mColorScheme == COLOR_SCHEME_WHITE)) || (!isWhite && (mColorScheme == COLOR_SCHEME_BLACK))) {
    		return;
    	}
    	
    	boolean needRefresh = mColorScheme != COLOR_SCHEME_UNSET;
    	
    	if (isWhite)
    		mColorScheme = COLOR_SCHEME_WHITE;
    	else
    		mColorScheme = COLOR_SCHEME_BLACK;
    	
    	switch (mColorScheme) {
    	case COLOR_SCHEME_WHITE:
    		
    		mPager.setListsBackgroundColor(Color.WHITE);
    		break;
    	case COLOR_SCHEME_BLACK: 
    		mPager.setListsBackgroundColor(Color.BLACK);
    		break;
        }    
        
        if (needRefresh) // we need this to recreate all views that could change their colors
        	fullRefresh();
    }
    
    private void setTable(String tableName, Integer preferedId) {
    	if (!mQuotesNavigator.getCurrentTableName().equals(""))
    		saveTopVisible();
    	TextView tvTitle = (TextView)findViewById(android.R.id.title);
    	
        if (tableName.equals(DatabaseHelper.TABLE_NAME_ABYSSBESTQUOTES)) {
        	mBtnQuotesSource.setImageResource(R.drawable.btn_favs_title);
    		mCurrentLastVisibleSuffix = LAST_VISIBLE_SUFFIX_ABYSS_BEST;
    		tvTitle.setText(getString(R.string.title_abyssbest));    		
    	} else if (tableName.equals(DatabaseHelper.TABLE_NAME_FAVORITES)) {
    		mBtnQuotesSource.setImageResource(R.drawable.btn_bash_title);
    		mCurrentLastVisibleSuffix = LAST_VISIBLE_SUFFIX_FAVORITES;
    		tvTitle.setText(getString(R.string.title_favs));
    	} else {
    		tvTitle.setText(R.string.app_name);
    	}
        int pos;
        if (preferedId != null)
        	pos = preferedId;
       	else
       		pos = mPreferences.getInt("top-visible" + mCurrentLastVisibleSuffix, QuotesNavigator.VERY_FIRST_QUOTE);        
        mQuotesNavigator.setCurrentTable(tableName, pos);    	
    }
      
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);            
        
        Window w = getWindow();
        w.requestFeature(Window.FEATURE_CUSTOM_TITLE);        
        setContentView(R.layout.ac_quotes);        
        w.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
        
        ((TextView)findViewById(android.R.id.title)).setText(R.string.app_name);
        
                   
        mContext = this;        
        
        mBtnFirst = (ImageButton)findViewById(R.id.btn_first);
        mBtnLast = (ImageButton)findViewById(R.id.btn_last);
        
        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);         
        
        mQuotesNavigator = new QuotesNavigator();        
        mQuotesNavigator.setOnPageChangedListener(new QuotesNavigator.OnPageChangedListener() {
        	@Override
			public void onPageChanged(int newPage, int quotesOnThisPage) {
        		int pc = mQuotesNavigator.getTotalPagesCount();
        		if (pc < 0)
        			pc = 0;
        		((TextView)findViewById(R.id.tv_subtitle)).setText(String.format(getString(R.string.pages_template), newPage, pc, quotesOnThisPage));
			}
        	
			@Override
			public void onJumpToPage(int newPage) {
				mPager.setInitialPage(newPage - 1);				
			}
		});
        
        mBtnFirst.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mQuotesNavigator.setTopQuote(QuotesNavigator.VERY_FIRST_QUOTE);				
			}
		});
        
        mBtnLast.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mQuotesNavigator.setTopQuote(QuotesNavigator.VERY_LAST_QUOTE);				
			}
		});          
              
        mBtnQuotesSource = (ImageButton)findViewById(R.id.btn_quotes_source);
        mBtnQuotesSource.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mQuotesNavigator.getCurrentTableName().equals(DatabaseHelper.TABLE_NAME_ABYSSBESTQUOTES))
		    		setTable(DatabaseHelper.TABLE_NAME_FAVORITES, null);		    		
		    	else
		    		setTable(DatabaseHelper.TABLE_NAME_ABYSSBESTQUOTES, null);		    		
		    	mPreferences.edit().putString("quotes-type", mQuotesNavigator.getCurrentTableName()).commit();			
			}
		});   
        
        mPager = (AbyssViewPager)findViewById(R.id.pager);
        mPager.init(R.layout.pager_list, new AbyssViewPager.ListsEventsCallback() {
			
			@Override
			public void onPageMovedForward() {				
				mQuotesNavigator.navigateNextPage();
			}
			
			@Override
			public void onPageMovedBack() {
				mQuotesNavigator.navigatePrevPage();
			}
			
			@Override
			public Cursor getThisPageCursor() {
				return mQuotesNavigator.getCurrentPageCursor();
			}
			
			@Override
			public Cursor getPrevPageCursor() {
				return mQuotesNavigator.getPrevPageCursor();
			}
			
			@Override
			public Cursor getNextPageCursor() {
				return mQuotesNavigator.getNextPageCursor();
			}
			
			@Override
			public SimpleCursorAdapter getAdapter(Cursor c) {
				QuoteAdapter adapter = new QuoteAdapter(mContext, R.layout.quote, 
						c, new String[] { DatabaseHelper.QUOTES_ID }, new int[] { android.R.id.text1 }, mQuotesNavigator);
				return adapter;
			}

			@Override
			public int getPagesCount() {				
				return mQuotesNavigator.getTotalPagesCount();
			}
		});       
        mColorScheme = COLOR_SCHEME_UNSET;    

        Integer preferedTopId = null;
        if ((savedInstanceState != null) && (savedInstanceState.containsKey("abyss-first-visible" + mCurrentLastVisibleSuffix))) {
        	preferedTopId = savedInstanceState.getInt("abyss-first-visible" + mCurrentLastVisibleSuffix);
        }       
        setTable(mPreferences.getString("quotes-type", DatabaseHelper.TABLE_NAME_ABYSSBESTQUOTES), preferedTopId);
        
        if (mPreferences.getBoolean("show-first-mesasge1", true)) {
        	Dialog d = new AlertDialog.Builder(this)
	        	.setTitle(R.string.app_name)
	        	.setMessage(Html.fromHtml(getString(R.string.first_run_message)))
	        	.setPositiveButton(R.string.ok, null)            	
	        	.create();		    	
        	d.show();
		
        	mPreferences.edit().putBoolean("show-first-mesasge1", false).commit();
        }
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
    	outState.putInt("abyss-first-visible" + mCurrentLastVisibleSuffix, getTopVisibleId());
    }      
    
    @Override  
    public boolean dispatchKeyEvent(KeyEvent event) {  
    	if (!mPreferences.getBoolean("prefs_scroll_volume_keys", true))
    		return super.dispatchKeyEvent(event); 
        if (event.getAction() == KeyEvent.ACTION_DOWN) {  
            switch (event.getKeyCode()) {  
	            case KeyEvent.KEYCODE_VOLUME_UP:  
	            	scrollListView(-1);
	                return true;  
	            case KeyEvent.KEYCODE_VOLUME_DOWN:  
	            	scrollListView(1);
	                return true;  
            }  
        }  
        if (event.getAction() == KeyEvent.ACTION_UP && (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP  
                || event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN)) {  
            return true;
        }  
        return super.dispatchKeyEvent(event);  
    }      
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu_quotesactivity, menu);
	    return true;
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK){
                	mQuotesNavigator.setTopQuote(QuotesNavigator.VERY_FIRST_QUOTE);
                	saveTopVisible();
                }; 
            default:
                break;
        }
    }   	

    public View getFirstVisibleView() {
        Rect r = new Rect();
        ListView lv = mPager.getCurrentListView();
        if (lv == null)
        	return null;
        int childCount = lv.getChildCount();
        for (int i = 0; i < childCount; ++i) {
            View listItem = lv.getChildAt(i);
            listItem.getLocalVisibleRect(r);
            if (r.top >= 0) { // if visible
                return listItem;
            }
        }
        return null;
    }
    
	private int getTopVisibleId() {
		int pos = -1;
		View v = getFirstVisibleView();
		ListView lv = mPager.getCurrentListView();
		if (v != null) {			
			pos = lv.getPositionForView(v);
		}
		if (pos < 0)
			return mQuotesNavigator.getTopQuote();
		else {
	    	Cursor c = ((QuoteAdapter)lv.getAdapter()).getCursor(); 
	    	c.moveToPosition(pos);		
			return c.getInt(c.getColumnIndex(DatabaseHelper.QUOTES_SOURCE_ID));			
		}
	}
	
	private void saveTopVisible() {
		mPreferences.edit().putInt("top-visible" + mCurrentLastVisibleSuffix, getTopVisibleId()).commit();
	}
	
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(downloadDoneReceiver);
        unregisterReceiver(refreshNeeded);
        saveTopVisible();
    } 
    

    @Override
    protected void onResume() {
        super.onResume();   
        if (!DatabaseHelper.checkDatabaseAvailable()) {
        	Dialog d = new AlertDialog.Builder(mContext)
	        	.setTitle(R.string.database_error_dialog_title)
	        	.setMessage(R.string.database_error_dialog)
	        	.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
	        		public void onClick(DialogInterface dialog, int whichButton) {
	        			finish();
	        		}
	        	})	        	
	        	.create();		    	
        	d.show();
		
        	
        }
        registerReceiver(downloadDoneReceiver, new IntentFilter(AbyssDownloaderService.ACTION_DOWNLOAD_ALL_DONE));
        registerReceiver(refreshNeeded, new IntentFilter(ACTION_NEED_REFRESH_DATA));
        checkColorScheme();
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    	case R.id.gotopage:
	    		if (mQuotesNavigator.getTotalPagesCount() <= 1)
	    			return true;
	    		LayoutInflater li = LayoutInflater.from(this);
	    		View dialogView = li.inflate(R.layout.gotopage, null);
	    		final EditText et = (EditText)dialogView.findViewById(R.id.et_page_number); 
		    	Dialog goDialog = new AlertDialog.Builder(this)
	            	.setTitle(R.string.gotopage)
	            	.setView(dialogView)
	            	.setPositiveButton(R.string.go, new DialogInterface.OnClickListener() {
	            		public void onClick(DialogInterface dialog, int whichButton) {
	            			try {
	        		        	int pageNum = Integer.parseInt(et.getText().toString());
	        		        	if (pageNum < 0)
	        		        		return;
		        	    		mQuotesNavigator.setTopQuoteByPageNum(pageNum);
	        		        } catch (NumberFormatException e) {	        		        
	        		        }
	        	    	}
	            	})
	            	.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
	            		public void onClick(DialogInterface dialog, int whichButton) {
	            		}
	            	})
	            	.create();		    	
		    	goDialog.show();	    		
	    		
	    		return true;       		        
		    case R.id.update:
		    	// start activity for update
        		Intent it = new Intent(this, DownloadActivity.class);
        		startActivityForResult(it, 0);        		
		        return true;	        		        
		    case R.id.export_favs:		
		    	
		    	ExportManager em = new ExportManager();
		    	final Uri fn = em.exportToAutonamedFile("select " + DatabaseHelper.QUOTES_SOURCE_ID + ", " +
		    		DatabaseHelper.QUOTES_POSTED + ", " + DatabaseHelper.QUOTES_QUOTE + " FROM " + DatabaseHelper.TABLE_NAME_FAVORITES +
		    		" ORDER BY 1 DESC");
		    	
		    	if (fn != null) {
			    	Dialog d = new AlertDialog.Builder(this)
		            	.setTitle(R.string.export)
		            	.setMessage(String.format(getString(R.string.export_done), fn.getPath()))
		            	.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
		            		public void onClick(DialogInterface dialog, int whichButton) {
		            			Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		        	        	emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		        	        	emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.export_mail_subject));		        	        	
	        	        		emailIntent.putExtra(Intent.EXTRA_STREAM, fn);
	        	        		emailIntent.setType("text/plain");		        	        	
		        	        	startActivity(Intent.createChooser(emailIntent, getString(R.string.export_mail_title)));  		    		    	
		            		}
		            	})  
		            	.setNegativeButton(R.string.no, null)
		            	.create();		    	
			    	d.show();
		    	} else {
		    		Dialog d = new AlertDialog.Builder(this)
		            	.setTitle(R.string.export)
		            	.setMessage(R.string.export_failed)
		            	.setPositiveButton(R.string.ok, null)            	
		            	.create();		    	
		    		d.show();
		    	}
		    	
		        return true;	        		        		        
		    case R.id.clear:	
		    	Dialog d = new AlertDialog.Builder(this)
	            	.setTitle(R.string.delete_all)
	            	.setMessage(R.string.delete_all_confirm)
	            	.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
	            		public void onClick(DialogInterface dialog, int whichButton) {
	            			DatabaseHelper.execSQL("delete from " + DatabaseHelper.TABLE_NAME_ABYSSBESTQUOTES);
	            			fullRefresh();	        		    	
	            		}
	            	})
	            	.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
	            		public void onClick(DialogInterface dialog, int whichButton) {
	            		}
	            	})
	            	.create();		    	
		    	d.show();
		        return true;		        
		    case R.id.preferences:	
        		Intent prefIntent = new Intent(this, PrefsActivity.class);
        		startActivity(prefIntent);
		        return true;		        
		    default:
		        return super.onOptionsItemSelected(item);
	    }
	}
	
    
    @Override
    protected void onStop() {
        super.onStop();
    }    
}

